import Character from '../base/character';
import DataBus from '../databus';
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../render';

const databus = new DataBus();

const PLAYER_WIDTH = 48;  // 角色宽度
const PLAYER_HEIGHT = 64; // 角色高度
const MOVE_SPEED = 5;     // 移动速度

export default class Player extends Character {
  constructor(canvas) {
    super('pics/lion.png', PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_WIDTH);

    // 保存canvas引用
    this.canvas = canvas;

    // 玩家默认位置
    this.x = 100;
    this.y = SCREEN_HEIGHT - PLAYER_HEIGHT - 100;

    // 移动相关
    this.moving = false;
    this.moveTargetX = this.x;
    this.moveTargetY = this.y;

    // 玩家特有属性
    this.maxHp = 240;
    this.hp = this.maxHp;
    this.baseAttack = 25;     // 基础攻击力
    this.baseDefense = 8;     // 基础防御力
    this.baseSpeed = MOVE_SPEED; // 基础速度
    this.attackInterval = 30;
    this.attackRange = 100;   // 减小攻击范围，使其更合理
    
    // 属性修饰符
    this.attackModifier = 1.0;  // 攻击力修饰符
    this.defenseModifier = 1.0; // 防御力修饰符
    this.speedModifier = 1.0;   // 速度修饰符
    
    // 设置攻击区域属性
    this.attackWidth = 80;    // 减小攻击区域宽度，约为角色宽度的1.5倍
    this.attackHeight = 80;   // 设置攻击区域高度，约为角色高度的1.2倍
    
    // 玩家独特系统
    this.level = 1;
    this.exp = 0;
    this.expToNextLevel = 100;
    this.critChance = 0.2;
    this.critMultiplier = 2.0;
    this.alwaysAnimate = true;
    
    // 受伤闪烁效果
    this.isBlinking = false;
    this.blinkCount = 0;
    this.blinkDuration = 3; // 闪烁持续3帧

    // 初始化事件监听
    this.initEvent();
    
    console.log('Player initialized at:', this.x, this.y);
  }

  initEvent() {
    // 确保canvas存在
    if (!this.canvas) {
      console.error('Canvas is not defined in Player.initEvent');
      return;
    }

    // 使用直接的触摸事件处理
    this.canvas.addEventListener('touchstart', ((e) => {
      e.preventDefault();
      
      if (!e.touches.length) return;
      
      const touch = e.touches[0];
      
      // 获取canvas的位置信息
      const canvasInfo = this.canvas.getBoundingClientRect();
      
      // 计算canvas的缩放比例
      const scaleX = this.canvas.width / canvasInfo.width;
      const scaleY = this.canvas.height / canvasInfo.height;
      
      // 将触摸坐标转换为canvas坐标，考虑缩放
      const canvasX = (touch.clientX - canvasInfo.left) * scaleX;
      const canvasY = (touch.clientY - canvasInfo.top) * scaleY;
      
      // 将转换后的坐标设置为移动目标
      this.moveTargetX = canvasX;
      this.moveTargetY = canvasY;
      this.moving = true;

      // 根据点击位置决定朝向
      if (canvasX < this.x) {
        this.direction = 'left';
      } else {
        this.direction = 'right';
      }
      
      console.log('Touch start:', touch.clientX, touch.clientY, '->', canvasX, canvasY, 'Current pos:', this.x, this.y);
    }).bind(this));

    this.canvas.addEventListener('touchmove', ((e) => {
      e.preventDefault();
      
      if (!e.touches.length) return;
      
      const touch = e.touches[0];
      
      // 获取canvas的位置信息
      const canvasInfo = this.canvas.getBoundingClientRect();
      
      // 计算canvas的缩放比例
      const scaleX = this.canvas.width / canvasInfo.width;
      const scaleY = this.canvas.height / canvasInfo.height;
      
      // 更新移动目标，考虑缩放
      this.moveTargetX = (touch.clientX - canvasInfo.left) * scaleX;
      this.moveTargetY = (touch.clientY - canvasInfo.top) * scaleY;
      this.moving = true;

      console.log('Touch move:', touch.clientX, touch.clientY, '->', this.moveTargetX, this.moveTargetY);
    }).bind(this));

    this.canvas.addEventListener('touchend', ((e) => {
      e.preventDefault();
      
      // 不要立即停止移动，让角色继续移动到目标位置
      console.log('Touch end, moving to target:', this.moveTargetX, this.moveTargetY);
    }).bind(this));
  }

  // 重写takeDamage方法，添加游戏结束检查
  takeDamage(damage, attacker = null) {
    const actualDamage = super.takeDamage(damage, attacker);
    
    if (this.hp <= 0) {
      this.hp = 0;
      databus.gameOver = true;
    }
    
    return actualDamage;
  }

  // 获得经验值
  gainExp(exp) {
    this.exp += exp;
    
    console.log('Gained exp:', exp, 'Total exp:', this.exp);
    
    // 检查是否升级
    if (this.exp >= this.expToNextLevel) {
      this.levelUp();
    }
  }

  // 升级
  levelUp() {
    this.level++;
    this.exp -= this.expToNextLevel;
    this.expToNextLevel = Math.floor(this.expToNextLevel * 1.5); // 下一级所需经验增加
    
    // 提升属性 - 增加升级收益
    this.maxHp += 25;  // 从20提升到25
    this.hp = this.maxHp; // 升级时恢复满血
    this.attack += 5;  // 从2提升到5
    this.defense += 2; // 从1提升到2
    this.critChance += 0.05; // 每级提升5%暴击率
    
    console.log('Level up! Now level:', this.level);
  }

  // 计算攻击伤害
  calculateDamage() {
    // 基础伤害
    let damage = this.attack;
    
    // 暴击判定
    const isCritical = Math.random() < this.critChance;
    if (isCritical) {
      damage *= this.critMultiplier;
      console.log('Critical hit! Damage multiplied by', this.critMultiplier);
    }
    
    return {
      damage: Math.floor(damage),
      isCritical
    };
  }

  // 自动攻击
  autoAttack() {
    if (++this.attackTimer >= this.attackInterval) {
      this.attackTimer = 0;
      
      // 寻找攻击范围内的所有敌人
      let targetsInRange = [];
      
      for (let enemy of databus.enemies) {
        if (enemy.isDying) continue; // 跳过正在死亡的敌人
        
        // 检查敌人是否在攻击范围内
        if (this.isTargetInAttackRange(enemy)) {
          targetsInRange.push(enemy);
        }
      }
      
      // 如果有敌人在攻击范围内
      if (targetsInRange.length > 0) {
        // 找到最近的敌人
        let nearestEnemy = targetsInRange[0];
        let minDistance = this.getDistanceTo(nearestEnemy);
        
        for (let i = 1; i < targetsInRange.length; i++) {
          const distance = this.getDistanceTo(targetsInRange[i]);
          if (distance < minDistance) {
            minDistance = distance;
            nearestEnemy = targetsInRange[i];
          }
        }
        
        // 朝向最近的敌人
        this.direction = nearestEnemy.x < this.x ? 'left' : 'right';
        
        // 计算伤害
        const attackResult = this.calculateDamage();
        
        // 对所有在范围内的敌人造成伤害
        for (let enemy of targetsInRange) {
          // 直接对敌人造成伤害，并传递攻击者（this）以触发击退效果
          enemy.takeDamage(attackResult.damage, this);
          
          // 显示伤害数字
          this.showDamageNumber(enemy, attackResult.damage, attackResult.isCritical);
        }
        
        // 播放攻击音效
        if (databus.music) {
          databus.music.playShoot();
        }
        
        // 添加攻击动画效果
        this.showAttackEffect();
        
        console.log('Player attacked', targetsInRange.length, 'enemies with damage:', 
                   attackResult.damage, attackResult.isCritical ? '(CRITICAL!)' : '');
      }
    }
  }
  
  // 显示对敌人造成的伤害
  showDamageToEnemy(enemy, damage, isCritical) {
    // 使用目标的showDamageNumber方法来显示伤害
    if (enemy && typeof enemy.showDamageNumber === 'function') {
      enemy.showDamageNumber(damage, isCritical);
    }
  }
  
  // 显示攻击效果
  showAttackEffect() {
    // 创建一个临时的攻击效果对象
    const attackEffect = {
      x: this.direction === 'left' ? this.x - 30 : this.x + this.width,
      y: this.y + this.height / 2 - 15,
      width: 30,
      height: 30,
      alpha: 1.0,
      lifeTime: 5, // 帧数
      update() {
        this.alpha -= 1 / this.lifeTime; // 逐渐消失
        return this.alpha > 0;
      },
      render(ctx) {
        ctx.save();
        ctx.globalAlpha = this.alpha;
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        ctx.beginPath();
        ctx.arc(this.x, this.y, 15, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();
      }
    };
    
    // 将攻击效果添加到数据总线
    if (!databus.attackEffects) {
      databus.attackEffects = [];
    }
    databus.attackEffects.push(attackEffect);
  }

  // 移动到目标位置
  moveToTarget() {
    if (!this.moving) return false;

    let moved = false;
    
    // 计算移动方向和距离
    const dx = this.moveTargetX - this.x;
    const dy = this.moveTargetY - this.y;
    
    // X轴移动
    if (Math.abs(dx) > MOVE_SPEED) {
      const moveX = dx > 0 ? MOVE_SPEED : -MOVE_SPEED;
      this.direction = dx > 0 ? 'right' : 'left';
      super.move(moveX, 0, 1);
      moved = true;
    } else {
      this.x = this.moveTargetX;
    }
    
    // Y轴移动
    if (Math.abs(dy) > MOVE_SPEED) {
      const moveY = dy > 0 ? MOVE_SPEED : -MOVE_SPEED;
      super.move(0, moveY, 1);
      moved = true;
    } else {
      this.y = this.moveTargetY;
    }
    
    // 如果已经到达目标位置，停止移动
    if (!moved) {
      this.moving = false;
      console.log('Reached target position:', this.x, this.y);
    }

    return moved;
  }

  // 重写update方法
  update() {
    const isMoving = this.moveToTarget();
    
    // 更新动画帧 - 无论是否移动都更新
    if (this.alwaysAnimate || isMoving) {
      super.update();
    }
    
    // 自动攻击
    this.autoAttack();
  }

  // 重写render方法，添加等级和HP显示，以及闪烁效果
  render(ctx) {
    // 处理闪烁效果
    if (this.isBlinking) {
      this.blinkCount++;
      if (this.blinkCount > this.blinkDuration) {
        this.isBlinking = false;
        this.blinkCount = 0;
      } else if (this.blinkCount % 2 === 0) {
        // 闪烁期间，每隔一帧切换可见性
        this.visible = !this.visible;
      }
    } else {
      this.visible = true;
    }
    
    if (!this.visible) return;
    
    super.render(ctx);
    
    // 仅绘制等级和HP
    ctx.save();
    ctx.font = '12px Arial';
    ctx.fillStyle = '#FFFFFF';
    ctx.textAlign = 'center';
    ctx.fillText(
      `Lv.${this.level} HP:${this.hp}/${this.maxHp}`,
      this.x + this.width / 2,
      this.y - 10
    );
    ctx.restore();
  }
}